import zmail
from pathlib import Path
from dotenv import load_dotenv
import os

# 加载环境变量
load_dotenv()

class EmailSender:
    def __init__(self, server_addr: str, username: str, password: str, port: int = 465, ssl: bool = True):
        """
        初始化邮件发送器
        
        :param server_addr: SMTP服务器地址 (如: smtp.163.com)
        :param username: 邮箱账号
        :param password: 邮箱密码/授权码
        :param port: SMTP端口 (默认465)
        :param ssl: 是否使用SSL (默认True)
        """
        self.server_config = {
            'smtp_host': server_addr,
            'smtp_port': port,
            'smtp_ssl': ssl,
            'username': username,   
            'password': password    
        }
        
        # 测试连接
        try:
            self.server = zmail.server(**self.server_config)
            print("邮件服务器连接成功")
        except Exception as e:
            raise ConnectionError(f"邮件服务器连接失败: {str(e)}")

    def send_email(
        self,
        recipients: list,
        subject: str,
        content: str = None,
        html: str = None,
        attachments: list = None,
        cc: list = None
    ) -> bool:
        """
        发送邮件
        
        :param recipients: 收件人列表 (可多个)
        :param subject: 邮件主题
        :param content: 纯文本内容 (与html二选一)
        :param html: HTML内容 (与content二选一)
        :param attachments: 附件路径列表
        :param cc: 抄送列表
        :return: 发送成功返回True，失败返回False
        """
        # 验证参数
        if not content and not html:
            raise ValueError("邮件内容不能为空，请提供content或html参数")
        
        # 构建邮件字典
        mail_content = {'subject': subject}
        
        if content:
            mail_content['content_text'] = content
        if html:
            mail_content['content_html'] = html
        
        # 处理附件
        if attachments:
            validated_attachments = []
            for path in attachments:
                p = Path(path)
                if p.exists() and p.is_file():
                    validated_attachments.append(str(p))
                else:
                    print(f"警告: 附件 {path} 不存在或不是文件，已跳过")
            if validated_attachments:
                mail_content['attachments'] = validated_attachments
        
        # 发送邮件
        try:
            self.server.send_mail(recipients, mail_content, cc=cc)
            print(f"邮件发送成功 -> 收件人: {', '.join(recipients)}")
            return True
        except Exception as e:
            print(f"邮件发送失败: {str(e)}")
            return False

# 使用示例
if __name__ == "__main__":
    # 配置邮箱信息 (请替换为实际值
    SERVER = os.getenv("SMTP_SERVER")    # 其他常见: smtp.qq.com, smtp.gmail.com
    USER = os.getenv("SMTP_USER")
    PASSWORD = os.getenv("SMTP_PASSWORD") 
    
    # 创建发送器实例
    sender = EmailSender(
        server_addr=SERVER,
        username=USER,
        password=PASSWORD,
    )
    
    html_content = """
    <html>
        <body>
            <h1>找回密码</h1>
            <p>您的验证码为: <strong>Abcdef</strong></p>
            <p>有效期: <strong>60分钟</strong></p>
        </body>
    </html>
    """
    
    sender.send_email(
        recipients=[os.getenv("SMTP_RECEIVER")],
        subject="找回密码",
        html=html_content,
    )